<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">后台登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { loginAPI } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const formRef = ref()
const form = ref({
  username: '',
  password: '',
})

const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const onLogin = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      const res = await loginAPI(form.value)
      // 假设返回格式为 { code: 0, data: { token, username, role }, message: '登录成功' }
      userStore.setUser(res.data)
      ElMessage.success('登录成功')
      router.push('/dashboard')
    } catch (err) {
      ElMessage.error(err.message || '登录失败')
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.login-card {
  width: 400px;
  padding: 30px;
}
.login-title {
  text-align: center;
  margin-bottom: 20px;
}
</style>
